﻿using sqlsearcher.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sqlsearcher.Services
{
    class JsonManager
    {
		private string modelFolder
        {
            get
            {
                return ConfigurationManager.AppSettings["modelFolder"].ToString();
            }
        }


        private string modelFile
        {
            get
            {
                return ConfigurationManager.AppSettings["modelFile"].ToString();
            }
        }

        private string dbTypeFile
        {
            get
            {
                return ConfigurationManager.AppSettings["dbTypeFile"].ToString();
            }
        }
        private string historyFile
        {
            get
            {
                return ConfigurationManager.AppSettings["historyFile"].ToString();
            }
        }

        /// <summary>
        /// 存储数据库类型
        /// </summary>
        public List<DbTypeInfo> GetDbTypes()
        {
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;

            var dbTypes = new List<DbTypeInfo>()
            {
                new DbTypeInfo(){Name="SQLServer",Id=1},
                new DbTypeInfo(){Name="MySQL",Id=2},
                new DbTypeInfo(){Name="Oracle",Id=3}
            };

            if (!File.Exists(debugPath + dbTypeFile))
            {
                using (StreamWriter sw = new StreamWriter(debugPath + dbTypeFile, false))
                {
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(dbTypes);
                    sw.Write(json);
                }
            }

            return dbTypes;
        }

        /// <summary>
        /// 存储历史成功的连接
        /// </summary>
        public void LogHistory(string server, string uid, string pwd,int dbType)
        {
            var model = new HistoryConnInfo();
            model.ServerName = server;
            model.Uid = uid;
            model.PassWord = pwd;
            model.DBType = dbType;
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;
            var models = new List<HistoryConnInfo>();

            if (File.Exists(debugPath + historyFile))
            {
                using (StreamReader sr = new StreamReader(debugPath + historyFile))
                {
                    models = Newtonsoft.Json.JsonConvert.DeserializeObject<List<HistoryConnInfo>>(sr.ReadToEnd());
                    sr.Close();
                }
            }
            if (models.Where(m => m.ServerName == model.ServerName && m.PassWord == model.PassWord && m.Uid == model.Uid).Count() > 0)
            {
                return;
            }
            models.Add(model);
            using (StreamWriter sw = new StreamWriter(debugPath + historyFile, false))
            {
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(models);
                sw.Write(json);
                sw.Close();
            }

        }

        internal List<HistoryConnInfo> GetHistorys()
        {
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;
            var models = new List<HistoryConnInfo>();

            try
            {
                if (File.Exists(debugPath + historyFile))
                {
                    using (StreamReader sr = new StreamReader(debugPath + historyFile))
                    {
                        models = Newtonsoft.Json.JsonConvert.DeserializeObject<List<HistoryConnInfo>>(sr.ReadToEnd());
                        sr.Close();
                    }
                }
            }
            catch
            {
                File.Delete(debugPath + historyFile);
            }


            return models;
        }

        /// <summary>
        /// 清除历史成功的连接
        /// </summary>
        public void ClearHistory()
        {
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;
            var models = new List<HistoryConnInfo>();
            if (File.Exists(debugPath + historyFile))
            {
                using (StreamWriter sw = new StreamWriter(debugPath + historyFile, true))
                {
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(models);
                    sw.Write(json);
                    sw.Close();
                }
            }
        }

		public Dictionary<string,string> GetModelTemplate()
        {
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;
            var modelStr = string.Empty;
            var dics = new Dictionary<string, string>();
            if(!Directory.Exists(debugPath + modelFolder))
            {
                Directory.CreateDirectory(debugPath + modelFolder);
            }
            var files = Directory.GetFiles(debugPath + modelFolder);
            foreach (var item in files)
            {
                var filename = Path.GetFileNameWithoutExtension(item);
                using (StreamReader sr = new StreamReader(item,Encoding.Default))
                {
                    modelStr = sr.ReadToEnd();
                    dics[filename] = modelStr;
                    sr.Close();
                }
            }
            return dics;
        }

		public void InsertModelTemplate(string filename,string filecontent)
        {
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;
            var path = debugPath + modelFolder;
            if (filename.IndexOf(".") != -1)
            {
                path += "\\" + filename ;
            }
            else
            {
                path += "\\" + filename + ".json";
            }
            
            using (StreamWriter sw = new StreamWriter(path,  false, Encoding.Default))
            {
                sw.Write(filecontent);
                sw.Close();
            }
        }

        internal void RemoveModelTemplate(string filename)
        {
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;
            var path = debugPath + modelFolder;
            if (filename.IndexOf(".") != -1)
            {
                path += "\\" + filename;
            }
            else
            {
                path += "\\" + filename + ".json";
            }

            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        internal void UpModelTemplate(string fileName, string txtContent)
        {
            var debugPath = AppDomain.CurrentDomain.BaseDirectory;
            var path = debugPath + modelFolder;
            if (fileName.IndexOf(".") != -1)
            {
                path += "\\" + fileName;
            }
            else
            {
                path += "\\" + fileName + ".json";
            }

            using (StreamWriter sw = new StreamWriter(path,false, Encoding.Default))
            {
                sw.Write(txtContent);
                sw.Close();
            }
        }
    }
}
